#include "bmperasertool.h"
#include "bmpeditor.h"
#include "action_changePixel.h"

const char * BMPEraserTool::NAME = "Eraser";
const char * BMPEraserTool::getName(){return NAME;}

bool BMPEraserTool::pressedTool(const int & a_mouseButton)
{
	bool handled = false;
	switch(a_mouseButton)
	{
	case SDL_BUTTON_WHEELUP:
		if(m_tool.w < MAX_SIZE){
			m_tool.w++;
			m_tool.h++;
		}
		handled = true;
		break;
	case SDL_BUTTON_WHEELDOWN:
		if(m_tool.w > 1)
		{
			m_tool.w--;
			m_tool.h--;
		}
		handled = true;
		break;
	case SDL_BUTTON_LEFT:
		m_state = ERASE;
		handled = true;
		break;
	case SDL_BUTTON_RIGHT:
		m_state = REPLACE;
		handled = true;
		break;
	}
	return draggedTool(a_mouseButton) || handled;
}

bool BMPEraserTool::releasedTool(const int & a_mouseButton)
{
	switch(a_mouseButton)
	{
	case SDL_BUTTON_LEFT:
	case SDL_BUTTON_RIGHT:
		m_state = IDLE;
		if(m_undo->getCurrentAction()->getName() == Action_ChangePixel::GETNAME())
		{
			Action_ChangePixel * change = (Action_ChangePixel *)m_undo->getCurrentAction();
			change->setCanBeAddedTo(false);
		}
		return true;
	}
	return false;
}

bool BMPEraserTool::draggedTool(const int & a_mouseButton)
{
	if(m_state != IDLE)
	{
		SRect area(m_tool);
		BMPEditor* bmpe = (BMPEditor*)getContext();
		SRect bitmapArea(bmpe->getBMP()->getArea());
		area.clip(bitmapArea);
		if(area.isValid())
		{
			int offColor = *bmpe->getPallette()->getSelectedColorIndex(
				BMPPalletteManager::COLOR_OFF);
			switch(m_state)
			{
			case ERASE:{
				Action_ChangePixel change(bmpe->getBMP(), area, offColor);
				m_undo->addAction(change, true);
				break;}
			case REPLACE:{
				int mainColor = *bmpe->getPallette()->getSelectedColorIndex(
					BMPPalletteManager::COLOR_MAIN);
				Action_ChangePixel change(bmpe->getBMP(), area, mainColor, offColor);
				m_undo->addAction(change, true);
				break;}
			}
		}
		return true;
	}
	return false;
}

void BMPEraserTool::draw(SDL_Surface * a_surface)
{
	BMPEditor* bmpe = (BMPEditor*)getContext();
	ZoomViewPanel * bv = bmpe->getZoomViewContent();
	SRect r(m_toolOnScreen);
	r.clip(*bv->getArea());
	if(r.isValid())
	{
		Uint32 color = bmpe->getPallette()->getSelectedColor(
			BMPPalletteManager::COLOR_OFF,a_surface->format);
		VSDL_FillRect(a_surface, &r, color);
	}
}